package org.mall.modules.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.mall.common.api.vo.Result;
import org.mall.common.constant.AppMessageTypeEnum;
import org.mall.common.constant.CommonStatusEnum;
import org.mall.common.system.query.QueryGenerator;
import org.mall.common.util.DateUtils;
import org.mall.common.util.ObjectUtils;
import org.mall.common.util.json.JacksonUtils;
import org.mall.modules.message.service.AppMessageService;
import org.mall.modules.pojo.common.AppMessageDTO;
import org.mall.modules.pojo.product.vo.ParamVo;
import org.mall.modules.pojo.product.vo.commodity.CommoditySpuVO;
import org.mall.modules.pojo.promotion.bo.ProductRecommendBO;
import org.mall.modules.pojo.shop.ShopPageBO;
import org.mall.modules.product.entities.CommoditySpu;
import org.mall.modules.product.entities.ProductMsg;
import org.mall.modules.product.service.ICommoditySpuService;
import org.mall.modules.promotion.service.ProductRecommendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 商品SPU
 * @Author: jeecg-boot
 * @Date:   2019-11-07
 * @Version: V1.0
 */
@RestController
@RequestMapping("/management")
@Slf4j
public class ManagementCommodityController {
    @Autowired
    private ICommoditySpuService commoditySpuService;
    @Autowired
    AppMessageService appMessageService;
    @Autowired
    private ProductRecommendService productRecommendService;
    @Autowired
    private ICommoditySpuService iCommoditySpuService;
    /**
     * 分页列表查询
     * @param goodsMain
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/web/list")
    public Result<IPage<ProductMsg>> queryPageList(CommoditySpuVO goodsMain,
                                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                   HttpServletRequest req) {
        Result<IPage<ProductMsg>> result = new Result<IPage<ProductMsg>>();
        CommoditySpu commoditySpu= ObjectUtils.copyObject(goodsMain,CommoditySpu.class);
        commoditySpu.setDeleted(false);
        QueryWrapper<CommoditySpu> queryWrapper = QueryGenerator.initQueryWrapper(commoditySpu, req.getParameterMap());
        Page page = new Page(pageNo, pageSize);
        IPage<ProductMsg> pageList = commoditySpuService.findByPage(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     *  查看商品详情
     * @return
     */
    @GetMapping(value = "/web/detail")
    public Result<?> detail(@RequestParam String id) {

        Long spuId=Long.parseLong(id);

        ProductMsg productMsg = commoditySpuService.getOneShopDetails(spuId);

        if (productMsg==null){
            return Result.error("商品不存在");
        }

        return Result.ok(productMsg);
    }

    /**
     * 单个商品下架功能
     * @param paramVo
     * @return
     */
    @PostMapping(value = "/web/lowerShelfGoods")
    public Result<?> lowerShelfGoods(@Valid @RequestBody ParamVo paramVo, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            return Result.error(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        // flag 1:上架，2：下架
       if(null != paramVo && "2".equals(paramVo.getFlag())){
            //下架需要把审核状态置为 未审核状态
            try {
                ProductRecommendBO recommendBO=productRecommendService.getProductBySpuId(Long.parseLong(paramVo.getSpuId()));
                if (recommendBO!=null){
                    return Result.error("该商品处于推荐位，请联系平台进行处理");
                }
                Long spuId=Long.parseLong(paramVo.getSpuId());
                ProductMsg productMsg = commoditySpuService.getOneShopDetails(spuId);
                boolean goods = commoditySpuService.changeProductSpuVisible(Long.parseLong(paramVo.getSpuId()),false);
                AppMessageDTO appMessageDTO = new AppMessageDTO();
                appMessageDTO.setContent("商品："+productMsg.getName()+"于"+DateUtils.formatDate(new Date())+"下架成功!");
                appMessageDTO.setTitle("商品下架");
                appMessageDTO.setCreator("管理员");
                appMessageDTO.setType(AppMessageTypeEnum.Commodity_Notification.getValue());
                appMessageDTO.setReceiver(productMsg.getSellerId());
                appMessageDTO.setTemplateId(1);
                appMessageDTO.setCreateTime(DateUtils.getDate());
                appMessageDTO.setEntitiesId(paramVo.getSpuId());
                appMessageService.sendAppMessageToUser(appMessageDTO);
            }catch (Exception e){
                log.error("下架操作出错",e.getMessage());
                return Result.error("下架操作出错!");
            }
        }else {
            return Result.error("管理端只有下架功能");
        }

       return Result.ok();
    }

    /**
     * 批量操作商品下架功能
     * @param paramVo
     * @return
     */
    @PostMapping(value = "/web/batchLowerShelfGoods")
    public Result<?> batchLowerShelfGoods(@Valid @RequestBody ParamVo paramVo,BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            return Result.error(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        List<Long> ids=new ArrayList<>();
        String[] stringIds=paramVo.getSpuId().split(",");
        for (String s:stringIds){
            ids.add(Long.parseLong(s));
        }
        Collection<CommoditySpu> dbList=commoditySpuService.listByIds(ids);
        List<ProductRecommendBO> bos= productRecommendService.getProductRecommendList(null, CommonStatusEnum.ENABLE.getValue());
        if (bos.stream().anyMatch(o->dbList.stream().anyMatch(a->o.getProductSpuId().equals(a.getId())))){
            return Result.error("存在处于推荐位置的商品无法进行批量下架,请联系平台处理");
        }
        if (!commoditySpuService.batchChangeProductSpuVisible(ids,false)){
            return Result.error("下架失败");
        }

        List<ProductMsg> allSellerId= commoditySpuService.getAllSellerId(Arrays.asList(paramVo.getSpuId().split(",")));
        List<String> sellerIds=allSellerId.stream().map(ProductMsg::getSellerId).collect(Collectors.toList());
        for(ProductMsg i:allSellerId){
            AppMessageDTO appMessageDTO = new AppMessageDTO();
            appMessageDTO
                    .setContent("商品："+i.getName()+"于"+DateUtils.formatDate(new Date())+"下架成功!!")
                    .setTitle("商品下架")
                    .setCreator("管理员")
                    .setType(AppMessageTypeEnum.Commodity_Notification.getValue())
                    .setReceiver(i.getSellerId())
                    .setTemplateId(1)
                    .setCreateTime(DateUtils.getDate())
                    .setEntitiesId(String.valueOf(i.getId()));
             appMessageService.sendAppMessageToUser(appMessageDTO);
        }


        return Result.ok();
    }

    /**
     * 单个商品审核操作（0：待审核。1审核通过）
     * @param paramVo
     * @return
     */
    @PostMapping(value = "/web/toExamineGoods")
    public Result<?> toExamineGoods(@Valid @RequestBody ParamVo paramVo , BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            return Result.error(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        //审核验证 如果审核状态返回  true :通过，false: 未通过  --未通过则可以审核  -- 通过则不可以审核
         Boolean toexamine=commoditySpuService.judgeToExamine(paramVo.getSpuId());
        if(toexamine){
            return Result.error("商品是已审核通过！！！");
        }else {
            //TODO  消息通知到商家审核不通过原因
            //审核标识(2：审核不通过，1：审核通过)
            if("1".equals(paramVo.getFlag()) && StringUtils.isNotBlank(paramVo.getSpuId())){
                try{
                    commoditySpuService.toExamineGoods(Long.parseLong(paramVo.getSpuId()),1);
                    //审核之后商品直接上架
                    iCommoditySpuService.changeProductSpuVisible(Long.parseLong(paramVo.getSpuId()),true);
                }catch (Exception e){
                    return Result.error("审核出错，请重新选择需要审核的商品");
                }
                Long spuId=Long.parseLong(paramVo.getSpuId());
                ProductMsg productMsg = commoditySpuService.getOneShopDetails(spuId);
                AppMessageDTO appMessageDTO = new AppMessageDTO();
                appMessageDTO.setContent("商品："+productMsg.getName()+"于"+DateUtils.formatDate(new Date())+"审核通过!!");
                appMessageDTO.setTitle("商品审核");
                appMessageDTO.setCreator("管理员");
                appMessageDTO.setType(AppMessageTypeEnum.Commodity_Notification.getValue());
                appMessageDTO.setReceiver(productMsg.getSellerId());
                appMessageDTO.setTemplateId(1);
                appMessageDTO.setCreateTime(DateUtils.getDate());
                appMessageDTO.setEntitiesId(paramVo.getSpuId());
                appMessageService.sendAppMessageToUser(appMessageDTO);
                return Result.ok("审核通过");
            }else {
                commoditySpuService.toExamineGoods(Long.parseLong(paramVo.getSpuId()),2);
                return Result.error("该商品不符合要求，请修改后重新提交审核");
            }
        }

    }

    /**
     * 批量审核商品操作（0：待审核。1审核通过,2：审核不通过）
     * @param paramVo
     * @return
     */
    @PostMapping(value = "/web/batchToExamineGoods")
    public Result<?> batchToExamineGoods(@Valid @RequestBody ParamVo paramVo,BindingResult bindingResult) {
        AppMessageDTO appMessageDTO ;
        if(bindingResult.hasErrors()){
            return Result.error(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        //TODO  消息通知到商家审核不通过原因
        Boolean result=commoditySpuService.batchToExamineGoods(new ArrayList<>(Arrays.asList(paramVo.getSpuId().split(","))).stream().map(a->Long.parseLong(a)).collect(Collectors.toList()), paramVo.getFlag());
        //批量审核之后 批量上架
        boolean flag = iCommoditySpuService.batchChangeProductSpuVisible(new ArrayList<>(Arrays.asList(
                paramVo.getSpuId().split(",")).stream().map(a->Long.parseLong(a)).collect(Collectors.toList())),true);
        if(result){
            List<ProductMsg> allSellerId= commoditySpuService.getAllSellerId(Arrays.asList(paramVo.getSpuId().split(",")));
            for (ProductMsg msg:allSellerId){
                appMessageDTO = new AppMessageDTO();
                appMessageDTO.setContent("商品审核成功");
                appMessageDTO.setTitle("商品审核");
                appMessageDTO.setCreator("管理员");
                appMessageDTO.setType(AppMessageTypeEnum.Commodity_Notification.getValue());
                appMessageDTO.setReceiver(msg.getSellerId());
                appMessageDTO.setTemplateId(1);
                appMessageDTO.setCreateTime(DateUtils.getDate());
                appMessageService.sendAppMessageToUser(appMessageDTO);
            }
        }
        return result?Result.ok():Result.error("审核失败");
    }

    /**
     * 删除商品
     * @param paramVo
     * @return
     */
    @PostMapping(value = "/web/delete")
    public Result<?> delete(@RequestBody ParamVo paramVo) {
        if(paramVo == null || StringUtils.isEmpty(paramVo.getSpuId())){
            return Result.error("请选择需要删除的商品！");
        }
        //TODO  消息通知到商家审核不通过原因
        Result<?> result = commoditySpuService.delete(paramVo);
        return result;
    }
}
